package com.yami.shop.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.bean.app.dto.UserBindingDto;
import com.yami.shop.bean.model.User;
import com.yami.shop.bean.model.UserBinding;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.dao.UserBindingMapper;
import com.yami.shop.dao.UserMapper;
import com.yami.shop.service.UserBindingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserBindingServiceImpl extends ServiceImpl<UserBindingMapper, UserBinding> implements UserBindingService {

    @Autowired
    private UserBindingMapper userBindingMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public boolean binding(UserBinding userBinding) {
        if(userBinding.getUserId().equals(userBinding.getRecommendUserId())){
            throw new YamiShopBindException("不能绑定自己");
        }

        User user=userMapper.selectById(userBinding.getUserId());
        if(ObjectUtil.isEmpty(user)){
            throw new YamiShopBindException("获取用户信息失败");
        }

        User recommendUser=userMapper.selectById(userBinding.getRecommendUserId());
        if(ObjectUtil.isEmpty(recommendUser)){
            throw new YamiShopBindException("获取推荐人信息失败");
        }

        List<UserBinding> list=lambdaQuery().eq(UserBinding::getUserId,userBinding.getUserId()).eq(UserBinding::getRecommendUserId,userBinding.getRecommendUserId()).list();
        if(list.size()>0){
            return true;
        }else{
            return this.save(userBinding);
        }
    }

    @Override
    public IPage<UserBindingDto> pageByRecommendUserId(IPage<UserBindingDto> page) {
        return userBindingMapper.pageByRecommendUserId(page);
    }
}
